/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.jwt.token;

import javax.servlet.http.HttpServletRequest;

import org.zfes.snowy.auth.shiro.exceptions.InvalidTokenException;
import org.zfes.snowy.core.util.ZStrUtil;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;

public class JWTTokenParser {

	public static String getTokenFromRequest(HttpServletRequest request,String tokenName){
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		String csrfTokenH = httpRequest.getHeader(tokenName);
		String csrfTokenP = httpRequest.getParameter(tokenName);
		return ZStrUtil.hasText(csrfTokenH)?csrfTokenH : csrfTokenP;
	}
	public static boolean  isJwtAuthTokenLegal(String tokenStr,String encryPubKey) {
		if(ZStrUtil.hasNoText(tokenStr)){
    		return false;
    	}
    	try {
    		 Jwts.parser().setSigningKey(encryPubKey).parse(tokenStr);
		} catch (SignatureException e) {
			return false;
		}
    	return true;
		
	}
	
	public static void  validateJwtAuthToken(String tokenStr,String encryPubKey) {
		if(!ZStrUtil.hasText(tokenStr)){
    		throw new InvalidTokenException("the token is empty or null.");
    	}
    	try {
		    Jwts.parser().setSigningKey(encryPubKey).parse(tokenStr);
		} catch (SignatureException e) {
			throw new InvalidTokenException("Invalid token string.");
		}
		
	}
	
	public static String parseUsername(String token, String encryPubKey) {
		String username = Jwts.parser()
						  .setSigningKey(encryPubKey)
						  .parseClaimsJws(token)
						  .getBody()
						  .getSubject();
		return username;
	}

	public  String parseId(String token, String encryPubKey) {
		String id = Jwts.parser()
					.setSigningKey(encryPubKey)
					.parseClaimsJws(token)
					.getBody()
					.getId();
		return id;
	}
	
}
